<template>
  <div class="addVisiting-container">
    <div class="addVisiting-save">
      <van-button
        type="primary"
        size="small"
        @click="onEdit"
        v-if="businessId && isDisabled && businessStatus.value !== 'YCJ'"
        >编 辑
      </van-button>
      <van-button color="#ccc" size="small" @click="onCancel" v-if="businessId && !isDisabled">取 消</van-button>
      <van-button type="primary" size="small" @click="onSubmit" v-if="!isDisabled" style="margin-left: 10px">保 存</van-button>
    </div>
    <van-form label-align="left" :disabled="isDisabled" ref="addBusinessForm">
      <van-cell-group>
        <van-field
          v-model="businessTitle"
          name="商机标题"
          label="商机标题"
          placeholder="商机标题"
          required
          :rules="[{ required: true, message: '请填写商机标题' }]"
        />
        <van-field
          v-model="expectedQuantity"
          name="意向数量"
          label="意向数量"
          placeholder="意向数量"
          type="digit"
          required
          :rules="[{ required: true, message: '请填写意向数量', validator: validatorQuantity }]"
        />
        <van-field
          v-model="businessSource.name"
          is-link
          readonly
          name="picker"
          label="商机来源"
          placeholder="点击选择商机来源"
          required
          :rules="[{ required: true, message: '请选择商机来源' }]"
          @click="!isDisabled ? (showBusinessSourcePicker = true) : ''"
        />
        <van-popup v-model:show="showBusinessSourcePicker" position="bottom">
          <van-picker
            :columns="businessSourceColumns"
            :columns-field-names="customBusinessSourceName"
            @confirm="onConfirmBusinessSource"
            @cancel="showBusinessSourcePicker = false"
          />
        </van-popup>
	      <van-field
		      v-model="salesperson"
		      name="销售人员"
		      label="销售人员"
		      placeholder="销售人员"
		      required
		      :rules="[{ required: true, message: '请填写销售人员' }]"
	      />
        <van-field v-model="documentNumber" name="单据号" label="单据号" disabled placeholder="单据号" />
        <van-field
          v-model="customerName"
          name="客户名称"
          label="客户名称"
          required
          placeholder="客户名称"
          :disabled="!!businessId"
          @input="inputCustomerName"
          :rules="[{ required: true, message: '请填写客户名称' }]"
        />
        <van-popup v-model:show="showCustomerListPicker" position="bottom">
          <van-picker
            :columns="customerList"
            :columns-field-names="customFieldName"
            @confirm="onConfirmCustomerList"
            @cancel="showCustomerListPicker = false"
          />
        </van-popup>
        <van-field
          v-model="linkman"
          name="联系人"
          label="联系人"
          placeholder="联系人"
          required
          :rules="[{ required: true, message: '请填写联系人' }]"
        />
        <van-field
          v-model="deliveryAddress"
          is-link
          readonly
          required
          name="area"
          label="交付地点"
          placeholder="点击选择交付地点"
          @click="!isDisabled ? (showDeliveryAddress = true) : ''"
          :rules="[{ required: true, message: '请填写交付地点' }]"
        />
        <van-popup v-model:show="showDeliveryAddress" position="bottom">
          <van-area :area-list="areaList" @confirm="onConfirmDeliveryAddress" @cancel="showDeliveryAddress = false" />
        </van-popup>
        <van-field
          v-model="detailStreet"
          name="详细街道"
          label="详细街道"
          placeholder="详细街道"
          required
          :rules="[{ required: true, message: '请填写详细街道' }]"
        />
        <van-field
          v-model="businessStage.text"
          is-link
          readonly
          name="picker"
          label="商机阶段"
          placeholder="点击选择商机阶段"
          required
          :rules="[{ required: true, message: '请选择商机阶段' }]"
          @click="!isDisabled ? (showBusinessStagePicker = true) : ''"
        />
        <van-popup v-model:show="showBusinessStagePicker" position="bottom">
          <van-picker
            :columns="businessStageColumns"
            @confirm="onConfirmBusinessStage"
            @cancel="showBusinessStagePicker = false"
          />
        </van-popup>
        <van-field
          v-model="businessStatus.text"
          name="商机状态"
          label="商机状态"
          placeholder="商机状态"
          readonly
          disabled
          required
          :rules="[{ required: true, message: '请填写商机状态' }]"
        />
        <!--				<van-field-->
        <!--					v-model="areaResult"-->
        <!--					is-link-->
        <!--					readonly-->
        <!--					required-->
        <!--					name="area"-->
        <!--					label="区域"-->
        <!--					placeholder="点击选择省市区"-->
        <!--					@click="showArea = true"-->
        <!--				/>-->
        <!--				<van-popup v-model:show="showArea" position="bottom">-->
        <!--					<van-area-->
        <!--						:area-list="areaList"-->
        <!--						@confirm="onConfirmArea"-->
        <!--						@cancel="showArea = false"-->
        <!--					/>-->
        <!--				</van-popup>-->
        <van-field
          v-model="areaResult"
          name="区域"
          label="区域"
          required
          placeholder="区域"
          :rules="[{ required: true, message: '请填写区域' }]"
        />
        <van-field
          v-model="cityName"
          name="城市"
          label="城市"
          required
          placeholder="城市"
          :rules="[{ required: true, message: '请填写城市' }]"
        />
        <van-field name="uploader" label="文件上传">
          <template #input>
            <van-uploader
              v-model="businessFile"
              :deletable="!isDisabled"
              :disabled="isDisabled"
              :after-read="afterRead"
              :before-delete="deleteBusinessFile"
              :preview-options="{closeable:'true'}"
            />
          </template>
        </van-field>
        <van-field v-model="remark" type="textarea" name="备注" label="备注" placeholder="备注" />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          v-if="businessId && isDisabled"
          @click="addBusinessQuote"
        >
          商机报价
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getDictionary } from '@/api/dictionary.js'
import { areaList } from '@/utils/area.js'
import { addBusiness, getBusinessDetail, getBusinessChannel } from '@/api/businessOpportunity.js'
import { Toast } from 'vant'
import request from '@/utils/request.js'
import { getCustomerInfo } from '@/api/customer.js'

export default {
  setup() {
    const router = useRouter()
    const route = useRoute()
    const addBusinessForm = ref(null)
    const state = reactive({
      userInfo: {},
      businessId: '',
      isDisabled: false,
      businessTitle: '',
      expectedQuantity: '',
	    salesperson: '',
      businessSource: '',
      showBusinessSourcePicker: false,
      businessSourceColumns: [],
      customBusinessSourceName: { text: 'name', value: 'id' },
      documentNumber: '',
      customerName: '',
      customerList: [],
      customFieldName: { text: 'Name', value: 'Name' },
      showCustomerListPicker: false,
      customerInfo: {},
      linkman: '',
      deliveryAddress: '',
      deliveryCode: [],
      showDeliveryAddress: false,
      detailStreet: '',
      businessStage: {},
      showBusinessStagePicker: false,
      businessStageColumns: [],
      businessStatus: {
        text: '未报价',
        value: 'WBJ'
      },
      areaResult: '',
      areaCode: [],
      showArea: false,
      cityName: '',
      businessFile: [],
      businessUploadFile: [],
      remark: ''
    })

    onMounted(async () => {
      initDictionary('business_stage')
      // getRelevanceClueList()
      await getBusinessSource()
      state.userInfo = JSON.parse(localStorage.getItem('userInfo'))
      console.log('userInfo:::', state.userInfo)

      if (route.query.id) {
        document.title = '编辑商机'
        state.businessId = route.query.id
        state.isDisabled = true
        getBusinessDetailInfo()
      }
    })

    const initDictionary = (code) => {
      getDictionary({ code }).then((res) => {
        const newDic = transOption(res)
        console.log('newDic::::', newDic)
        if (code === 'business_stage') {
          state.businessStageColumns = newDic
        }
      })
    }

    const transOption = (data) => {
      const newDate = []
      data.map((item) => {
        const obj = {
          text: item.dictValue,
          value: item.dictKey
        }
        newDate.push(obj)
      })
      return newDate
    }

    const getBusinessSource = () => {
      return new Promise((resolve, reject) => {
        getBusinessChannel({ type: 'SJ' }).then((res) => {
          state.businessSourceColumns = res
          resolve()
        })
      })
    }

    const getBusinessDetailInfo = () => {
      getBusinessDetail({ id: state.businessId }).then((res) => {
        if (res.channelCode) {
          state.businessSource = state.businessSourceColumns.find((item) => item.id === res.channelCode)
        }
        state.businessTitle = res.title
        state.expectedQuantity = res.expectedQuantity
        state.salesperson = res.salesperson
        state.documentNumber = res.sn
        state.customerName = res.customerName
        state.linkman = res.contactsName
        state.deliveryAddress = res.address
        state.detailStreet = res.detailAddress
        state.businessStage.text = res.businessStageMsg
        state.businessStage.value = res.businessStage
        state.businessStatus.text = res.businessStatusMsg
        state.businessStatus.value = res.businessStatus
        state.areaResult = res.region
        state.cityName = res.city
        if (res?.enclosureList?.length) {
          res.enclosureList.forEach((item) => {
            state.businessFile.push({
              url: item.value
            })
          })
          state.businessUploadFile = res.enclosureList
        }
        state.remark = res.remark
      })
    }

    const inputCustomerName = (value) => {
      getCustomerInfo(value.data).then((res) => {
        console.log('res:::', res)
        if (res.length) {
          state.customerList = res
          state.showCustomerListPicker = true
        }
      })
    }

    const onConfirmCustomerList = (value) => {
      state.customerName = value.Name
      state.showCustomerListPicker = false
    }

    const onConfirmBusinessSource = (value) => {
      state.businessSource = value
      state.showBusinessSourcePicker = false
      console.log('businessSource:::', state.businessSource)
    }

    const onConfirmDeliveryAddress = (value) => {
      console.log('选择省市区')
      let city = ''
      let cityCode = []
      value.forEach((item) => {
        city += item.name
        cityCode.push(item.code)
      })
      state.deliveryAddress = city
      state.deliveryCode = cityCode
      state.showDeliveryAddress = false
    }

    const onConfirmBusinessStage = (value) => {
      if (value) {
        state.businessStage = value
      }

      state.showBusinessStagePicker = false
    }

    const onConfirmArea = (value) => {
      console.log('选择省市区')
      let city = ''
      let cityCode = []
      value.forEach((item) => {
        city += item.name
        cityCode.push(item.code)
      })
      state.areaResult = city
      state.areaCode = cityCode
      state.showArea = false
    }

    const onConfirmVisitingDate = (value) => {
      console.log('value::::', value)
      console.log('visitingDate;:::', state.visitingDate)
      state.showVisitingDatePicker = false
    }

    const onConfirmClue = (value) => {
      console.log('value:::::::', value)
      if (value) {
        state.relevanceClue.value = value
      }
      state.showCluePicker.value = false
    }

    const getLocation = () => {
      console.log('点击定位')
    }

    const deleteBusinessFile = (file, indexData) => {
      state.businessFile.splice(indexData.index, 1)
      state.businessUploadFile.splice(indexData.index, 1)
    }

    const afterRead = (file) => {
      // 此时可以自行将文件上传至服务器
      console.log(file)
      const formData = new FormData()
      formData.append('file', file.file)

      // 示例使用 axios 进行文件上传
      uploadFile(formData)
    }

    const uploadFile = (formData) => {
      // 使用你的上传接口地址替换以下 URL
      const url = 'web-service/oss/endpoint/put-file'
      // 这里使用 axios 作为请求示例
      request
        .post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: (progressEvent) => {
            // 这里可以获取上传进度
            console.log(progressEvent)
          }
        })
        .then((response) => {
          // 上传成功处理
          console.log('response::::', response)
          console.log('followUpFile::::', state.businessFile)
          state.businessUploadFile.push({
            label: response.originalName,
            value: response.link
          })
        })
        .catch((error) => {
          // 上传失败处理
          console.error(error)
        })
    }

    const onEdit = () => {
      state.isDisabled = false
    }

    const onCancel = () => {
      state.isDisabled = true
    }

    const validatorQuantity = (val) => {
      console.log('222', /^[1-9]\d*$/.test(val))
      return /^[1-9]\d*$/.test(val)
    }

    const onSubmit = () => {
      addBusinessForm.value.validate().then(() => {
        let params = {
          title: state.businessTitle,
          expectedQuantity: state.expectedQuantity,
	        salesperson: state.salesperson,
          channelCode: state.businessSource.id,
          // sn: state.documentNumber,
          customerName: state.customerName,
          contactsName: state.linkman,
          address: state.deliveryAddress,
          addressCode: state.deliveryCode.join(','),
          addressCodeList: state.deliveryCode,
          detailAddress: state.detailStreet,
          businessStage: state.businessStage.value,
          businessStatus: state.businessStatus.value,
          region: state.areaResult,
          city: state.cityName,
          enclosureList: state.businessUploadFile,
          remark: state.remark,
          ownerUserExt: state.userInfo.realName + state.userInfo.deptName,
          ownerUserId: state.userInfo.id,
          ownerUser: state.userInfo.realName,
          ownerDeptId: state.userInfo.deptId,
          ownerDeptName: state.userInfo.deptName,
          ownerPhoneNumber: state.userInfo.phone
        }

        if (state.businessId) {
          params.id = state.businessId
        }
        console.log('params;:::', params)
        addBusiness(params).then((res) => {
          console.log('res::::', res)
          Toast.success(`${state.businessId ? '编辑' : '新增'}商机成功！`)
          if (state.businessId) {
            onCancel()
          } else {
            setTimeout(() => {
              router.back()
            }, 500)
          }
        })
        console.log('params;:::', params) // 暂未对接新增商机
      })
    }

    const addBusinessQuote = () => {
      console.log('商机报价')
      router.push({ path: './addQuote', query: { businessId: state.businessId } })
    }

    return {
      areaList,
      addBusinessForm,
      ...toRefs(state),
      onEdit,
      onCancel,
      onSubmit,
      inputCustomerName,
      onConfirmCustomerList,
      onConfirmBusinessSource,
      onConfirmDeliveryAddress,
      onConfirmBusinessStage,
      addBusinessQuote,
      onConfirmVisitingDate,
      onConfirmClue,
      getLocation,
      onConfirmArea,
      afterRead,
      deleteBusinessFile,
      validatorQuantity
    }
  }
}
</script>

<style scoped lang="less">
.addVisiting-container {
  .addVisiting-save {
    display: flex;
    justify-content: flex-end;
    margin: 20px;
  }
}
</style>
